import React, { ChangeEvent, useEffect, useState } from 'react'
import { useHistory, Link } from 'react-router-dom'
import * as api from '../../services/api'
import style from './style.module.less'
import { Form, Input, Button, Checkbox, message } from 'antd'
import { UserOutlined, LockOutlined } from '@ant-design/icons'

export default function Login() {
  let token: string
  let remember: boolean = true

  let history = useHistory()

  const limit: number = 10

  const [account, setAccount] = useState<string>('')
  const [pwd, setPwd] = useState<string>('')

  useEffect(() => {
    let ac = localStorage.getItem('account')
    let pw = localStorage.getItem('pwd')
    if (ac !== null) setAccount(ac)
    if (pw !== null) setPwd(pw)
  }, [])

  async function login() {
    try {
      if (account !== '' && pwd !== '') {
        let res = await api.login(account, pwd)
        if (res.data.stat === 'ok') {
          token = res.data.data.token
          message.destroy()
          message.success('登录成功')
          history.push(`/main/${token}`)
        } else {
          message.destroy()
          message.error(res.data.msg)
        }
      } else {
        if (account === '') {
          message.destroy()
          message.error('请输入你的用户名!')
        } else {
          if (pwd === '') {
            message.destroy()
            message.error('请输入你的密码!')
          }
        }
      }
    } catch (e) {
      throw e
    }
  }

  function getAccount() {
    let ac = localStorage.getItem('account')
    if (ac !== null) return ac
  }

  function getPwd() {
    let pw = localStorage.getItem('pwd')
    if (pw !== null) return pw
  }

  function setAccountOnChange(e: ChangeEvent<HTMLInputElement>) {
    if (e.target.value.length <= limit) {
      setAccount(e.target.value)
      if (remember) localStorage.setItem('account', e.target.value)
    } else {
      setAccount(e.target.value.slice(0, limit))
      if (remember)
        localStorage.setItem('account', e.target.value.slice(0, limit))
      message.destroy()
      message.error(`用户名长度不能超过${limit}个字符`)
    }
  }

  function setPwdOnChange(e: ChangeEvent<HTMLInputElement>) {
    if (e.target.value.length <= limit) {
      setPwd(e.target.value)
      if (remember) localStorage.setItem('pwd', e.target.value)
    } else {
      setPwd(e.target.value.slice(0, limit))
      if (remember) localStorage.setItem('pwd', e.target.value.slice(0, limit))
      message.destroy()
      message.error(`用户名长度不能超过${limit}个字符`)
    }
  }

  function rememberUser() {
    remember = !remember
    if (!remember) {
      localStorage.removeItem('account')
      localStorage.removeItem('pwd')
    } else {
      if (account !== '') localStorage.setItem('account', account)
      if (pwd !== '') localStorage.setItem('pwd', pwd)
    }
  }

  return (
    <div>
      <React.Fragment>
        <div className={style.box}>
          <Form name="login" className={style.form_login}>
            <span>木易创作</span>
            <Form.Item className={style.form_login_input_item}>
              <Input
                prefix={<UserOutlined />}
                type="text"
                value={account}
                defaultValue={getAccount()}
                onChange={(event) => setAccountOnChange(event)}
              />
            </Form.Item>
            <Form.Item className={style.form_login_input_item}>
              <Input
                prefix={<LockOutlined />}
                type="password"
                value={pwd}
                defaultValue={getPwd()}
                onChange={(e) => setPwdOnChange(e)}
              />
            </Form.Item>
            <Form.Item className={style.form_login_checkbox_item}>
              <Form.Item name="remember" valuePropName="checked" noStyle />
              <Checkbox
                className={style.form_login_checkbox}
                defaultChecked={remember}
                onChange={rememberUser}>
                {' '}
                记住密码
              </Checkbox>
              <Link className={style.form_login_registry} to="/registry">
                没有账号？点击注册
              </Link>
            </Form.Item>
            <Form.Item>
              <Button
                type="primary"
                htmlType="submit"
                className={style.form_login_button}
                onClick={login}>
                登录
              </Button>
            </Form.Item>
          </Form>
        </div>
      </React.Fragment>
    </div>
  )
}
